package iss.java;

import java.util.concurrent.locks.*;
import java.lang.*;

import iss.java.list.MyList;
import iss.java.list.Node;

/**
 * Created by wenke on 2016/9/16.
 */
class Main_A extends Thread{
    public static Lock lock = new ReentrantLock();
    public static void main(String[] args) {
        // TODO: Implement a multithreaded test case against requirement A.
        //create a list
        MyList list = new MyList();
        list.insert(list.getHead(), 5);
        list.insert(list.getHead(), 4);
        list.insert(list.getHead(), 3);
        list.insert(list.getHead(), 2);
        list.insert(list.getHead(), 1);

        // Traverse from head to tail, exclude head and tail
        for (Node n = list.getHead().getNext(); n!=list.getTail(); n=n.getNext()) {
            System.out.printf("%d ", n.getData());
        }//end for
        System.out.println();

        //create a node type
        Node n=list.getHead();
        System.out.println("The initial data is:"+n.getData());
        int x=n.getData();

        Thread ta = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 5; ++i) {
                    lock.lock();
                    try {
                        int x=n.getData();
                        x+=2;
                    }
                    finally {
                        lock.unlock();
                    }
                }
            }
        };

        Thread tb = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 5; ++i) {
                    lock.lock();
                    try {
                        int x=n.getData();
                        x -=2;
                    }
                    finally {
                        lock.unlock();
                    }
                }
             
            }
        };

        ta.start();
        tb.start();
        
        System.out.printf("The final result is:%d\n", x);
    }//end method main

}//end class Main_A


